package cn.gok.manage.web;

import cn.gok.manage.service.IOrderService;
import cn.gok.util.ResultData;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import javax.xml.transform.Result;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author: 鸭鸭
 * @ClassName:OrderController
 * @Package:cn.gok.manage.web
 * @Description:
 * @date: 2021/8/9
 * @time: 14:34
 */
@Slf4j
@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    IOrderService orderService;
    /*
     *创建订单
     */
    @RequestMapping(value = "/create.do", method = RequestMethod.GET)
    @ResponseBody
    public ResultData createOrderByShippingId(@RequestParam("shippingId") int shippingId){
        //拦截器获取userId
        int userId = 26;
        return orderService.createOrderByShippingId(userId,shippingId);
    }

    /*
    * 获取订单的商品信息
    * */
    @RequestMapping(value = "/get_order_cart_product.do", method = RequestMethod.GET)
    @ResponseBody
    public ResultData getOrderCartProduct(){
        //拦截器获取userId
        int userId = 26;
        return orderService.getCartOrderChecked(userId);
    }

    /*
    * 根据用户Id获取订单List
    * */
    @RequestMapping(value = "/list.do", method = RequestMethod.GET)
    @ResponseBody
    public ResultData getOrderList(@RequestParam(value="pageSize",required = false,defaultValue = "10") int pageSize,
                                   @RequestParam(value="pageNum",required = false,defaultValue = "1") int pageNum){
        //拦截器获取UserId
        int userId = 26;
        return orderService.getOrderList(userId,pageNum,pageSize);
    }
    /*
    * 根据订单No查询订单详细信息
    * */
    @RequestMapping(value = "/detail.do", method = RequestMethod.GET)
    @ResponseBody
    public ResultData GetOrderDetailByOrderNo(@RequestParam("orderNo") long orderNo){
        return orderService.getOrderDetailByOrderNo(orderNo);
    }

    /*
    * 取消订单
    * */
    @RequestMapping(value = "/cancel.do", method = RequestMethod.GET)
    @ResponseBody
    public ResultData CancelOrderByOrderId(@RequestParam("orderNo") long orderNo){
        return orderService.cancelOrderByOrderNo(orderNo);
    }

    /*
    * 支付
    * */
    @RequestMapping(value = "/pay.do",method = RequestMethod.POST)
    @ResponseBody
    public ResultData pay(long orderNo) throws IOException {
        String path = ResourceUtils.getURL("classpath:").getPath();
        //在类路径下创建static/upload路径
        File upload = new File(path,"static/upload");
        if(!upload.exists()){
            upload.mkdirs();
        }
        return orderService.pay(upload.getAbsolutePath(),orderNo);
    }

    /*
    * 当用户支付成功后，支付宝官网会自动调用该地址，提示支付情况
    * */
    @RequestMapping("/alipay_callback.do")
    @ResponseBody
    public Object alipayCallback(HttpServletRequest request){

        //拦截器获取用户Id
        int userId = 26;

        //获取支付宝返回的信息
        Map<String,String[]> paramterMap = request.getParameterMap();

        //构建调用支付宝签证方法时，需要的map参数
        Map<String,String> aliMaps = new HashMap<>();

        Set<Map.Entry<String,String[]>> entries = paramterMap.entrySet();
        for(Map.Entry<String,String[]> entry:entries){
            String key = entry.getKey();
            String[] value = entry.getValue();
            String str = "";
            for(int i=0;i<value.length;i++){
                  str=(i==value.length-1) ? str+value[i] : str+value[i]+",";
            }
            aliMaps.put(key,str);
        }

        boolean b=false;
        try {
           b= AlipaySignature.rsaCheckV2(aliMaps, Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());
        } catch (AlipayApiException e) {
            log.error("支付宝签证异常",e);
        }
        if(b=false){
            return ResultData.fail("非法请求，签证验证失败");

        }

        //如果是支付宝发起的回调，验数据的正确性，如订单是否正确，金额是否正确等
        ResultData resultData = orderService.alipayCallback(aliMaps,userId);
        if(resultData.getStatus().equals("0")){
            return "success";
        }

        return resultData;
    }
    /*
    * 查询订单支付状态
    * */
    @RequestMapping("/query_order_pay_status.do")
    @ResponseBody
    public ResultData queryOrderPayStatus(long orderNo) {
        return orderService.selectOrderPayStatus(orderNo);

    }

    @ResponseBody
    @RequestMapping("/listAll.do")
    public ResultData getAllOrder(@RequestParam(defaultValue = "1")int pageNum,
                                  @RequestParam(defaultValue = "10") int pageSize,
                                  Long orderNo){
        return orderService.getAllOrder(pageNum,pageSize,orderNo);
    }

    @ResponseBody
    @RequestMapping("/search.do")
    public ResultData queryOrderByOrderNo(long orderNo){
        return orderService.queryOrderByOrderNo(orderNo);
    }

    @ResponseBody
    @RequestMapping("/orderDetail.do")
    public ResultData queryOrderDetailByOrderNo(long orderNo){
        return orderService.queryOrderDetailByOrderNo(orderNo);
    }

    @ResponseBody
    @RequestMapping("/send_goods.do")
    public ResultData sendGood(long orderNo){
        return orderService.sendGoods(orderNo);
    }





}
